<template>
  <el-card class="notification-container">
    <div class="header">
      <h3>我的通知</h3>
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="fetchNotifications"
          :loading="loading"
        >
          刷新列表
        </el-button>
        <el-tag type="warning" v-if="unreadCount > 0">
          未读通知: {{ unreadCount }}
        </el-tag>
      </div>
    </div>

    <el-table
      :data="filteredNotifications"
      stripe
      border
      v-loading="loading"
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column
        prop="type"
        label="类型"
        width="120"
        sortable
      >
        <template #default="{ row }">
          <el-tag :type="getTagType(row.type)">
            {{ formatType(row.type) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="content"
        label="内容"
        min-width="200"
      />

      <el-table-column
        prop="created_at"
        label="时间"
        width="180"
        sortable
      />

      <el-table-column
        prop="sender_name"
        label="发送人"
        width="150"
      />

      <el-table-column
        label="状态"
        width="120"
        sortable
        prop="is_read"
      >
        <template #default="{ row }">
          <el-tag :type="row.is_read ? 'success' : 'warning'">
            {{ row.is_read ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        width="180"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            :type="row.is_read ? 'info' : 'primary'"
            :disabled="row.is_read"
            @click="markAsRead(row)"
          >
            {{ row.is_read ? '已读' : '标记已读' }}
          </el-button>
          <el-popconfirm
            title="确定要删除这条通知吗？"
            @confirm="deleteNotification(row.id)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" v-if="notifications.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="totalNotifications"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
import {
  getNotificationList,
  markNotificationAsRead,
  deleteNotification as deleteNotificationApi,
  getUnreadNotifications
} from '@/api/notification'
import { getUserInfo } from '@/api/user'
import { ElMessage } from 'element-plus'

// 数据状态
const notifications = ref([])
const loading = ref(false)
const unreadCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const sortProp = ref('created_at')
const sortOrder = ref('descending')

// 获取通知列表
const fetchNotifications = async () => {
  loading.value = true
  try {
    const [notificationsRes, unreadRes] = await Promise.all([
      getNotificationList(),
      getUnreadNotifications()
    ])

    if (notificationsRes?.data?.code === 200) {
      const notificationsData = notificationsRes.data.data || []
      const usersCache = {}

      // 获取发送者信息
      for (const item of notificationsData) {
        if (!usersCache[item.authorId]) {
          try {
            const userRes = await getUserInfo(item.authorId)
            if (userRes?.data?.code === 200) {
              usersCache[item.authorId] = userRes.data.data.username
            }
          } catch (error) {
            console.error('获取用户信息失败:', error)
            usersCache[item.authorId] = '未知用户'
          }
        }
      }

      notifications.value = notificationsData.map(item => ({
        id: item.id,
        type: item.type,
        content: item.content || '暂无内容',
        created_at: dayjs(item.createdAt).format('YYYY-MM-DD HH:mm'),
        is_read: item.isRead === 1,
        sender_id: item.authorId,
        sender_name: usersCache[item.authorId] || '未知用户'
      }))
    }

    if (unreadRes?.data?.code === 200) {
      unreadCount.value = unreadRes.data.data.count || 0
    }
  } catch (error) {
    console.error('获取通知失败:', error)
    ElMessage.error('获取通知失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 标记为已读
const markAsRead = async (row) => {
  if (row.is_read) return

  try {
    const res = await markNotificationAsRead(row.id)
    if (res?.data?.code === 200) {
      row.is_read = true
      unreadCount.value -= 1
      ElMessage.success('标记为已读成功')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

// 删除通知
const deleteNotification = async (id) => {
  try {
    const res = await deleteNotificationApi(id)
    if (res?.data?.code === 200) {
      ElMessage.success('删除通知成功')
      fetchNotifications()
    }
  } catch (error) {
    console.error('删除通知失败:', error)
    ElMessage.error('删除通知失败')
  }
}

// 格式化通知类型
const formatType = (type) => {
  const typeMap = {
    approval: '审批通知',
    reminder: '提醒通知',
    system: '系统通知'
  }
  return typeMap[type] || `未知类型 (${type})`
}

// 获取标签类型
const getTagType = (type) => {
  const typeToTag = {
    approval: 'success',
    reminder: 'warning',
    system: 'info'
  }
  return typeToTag[type] || ''
}

// 分页和排序
const totalNotifications = computed(() => notifications.value.length)
const filteredNotifications = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value

  return [...notifications.value]
    .sort((a, b) => {
      if (sortOrder.value === 'ascending') {
        return a[sortProp.value] > b[sortProp.value] ? 1 : -1
      } else {
        return a[sortProp.value] < b[sortProp.value] ? 1 : -1
      }
    })
    .slice(start, end)
})

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleSortChange = ({ prop, order }) => {
  sortProp.value = prop
  sortOrder.value = order
}

// 初始化
onMounted(() => {
  fetchNotifications()
})
</script>

<style scoped>
.notification-container {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}

.el-tag {
  margin-right: 5px;
}
</style>
